import java.util.PriorityQueue;

class Solution2 {
    int[] st;
    PriorityQueue<Integer> queue;
    public int kthLargestPerfectSubtree(TreeNode root, int k) {
        if(root==null){
            return -1;
        }
        st=new int[2010];
        queue=new PriorityQueue<>((a,b)->b.compareTo(a));

        int t=seek(root);
        queue.offer(t);

        int ans=0;
        while (!queue.isEmpty()){
            k--;
            if(k==0){
                ans=queue.poll();
            }
            queue.poll();
        }
        if(k>0){
            return -1;
        }
        return ans;
    }
    public int seek(TreeNode root){
        if(root.right==null && root.left==null){
            queue.offer(1);
            return 1;
        }
        int left=root.left==null ? 0:seek(root.left);
        int right=root.right==null ? 0:seek(root.right);
        if((left==right)&&left!=0){
            queue.offer(left*2);
            return left*2;
        }else{
            return 0;
        }
    }




























    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
